﻿
using System.FileServer.Client;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using WebResource.ApiModels;

namespace WebResource
{
    [ApiController]//记住这个单词
    [Route("webresources/PointFile")]//记住这个
    public class PointFileServer : GCCAPIControllerBase
    {
        public PointFileServer(AbsGCCContext context) : base(context)
        {
        }

        [HttpGet("items")]
        public DataResponse<List<GetPointFileItemsResponse>> GetAllItems([FromQuery] GetPointFileItemsRequest request)
        {

            var pointFileServer = GCCContext.GetConfigByPath(new string[] { base.GCCContext.PointName ?? "", "FileServer" });

            var items = Manager.GRPCGetAllItems(pointFileServer, request.PageIndex ?? 1, request.PageSize, GCCContext.EventID ?? "");
            if (items is null)
            {
                return IllegalRequest<List<GetPointFileItemsResponse>>();
            }

            var res = new List<GetPointFileItemsResponse>();

            foreach (var item in items.Items)
            {
                res.Add(new GetPointFileItemsResponse()
                {
                    CheckCode = item.CheckCode,
                    Created = DateTime.FromFileTimeUtc(item.Created),
                    CreatedBy = item.CreatedBy,
                    CurrentName = item.CurrentName,
                    CurrentSavePoint = item.CurrentSavePoint,
                    OriginalName = item.OriginalName,
                    ID = item.ID,
                    Modified = DateTime.FromFileTimeUtc(item.Modified),
                    ModifiedBy = item.ModifiedBy,
                });
            }

            return HandleData(res, items.DataCount);
        }


        [HttpGet("items/{fid}")]
        public ActionResult GetFile([FromRoute] long fid, [FromQuery] string mimeType = "application/octet-stream")
        {
            var pointFileServer = GCCContext.GetConfigByPath(new string[] { base.GCCContext.PointName ?? "", "FileServer" });

            var item = Manager.GRPCGetFileByID(pointFileServer, fid, GCCContext.EventID ?? "");
            if (item is null)
            {
                return new EmptyResult();
            }

            var fs = System.IO.File.OpenRead(item.FilePath);
            FileStreamResult fsr = new(fs, mimeType);
            if (mimeType == "application/octet-stream")
            {
                fsr.FileDownloadName = new FileInfo(item.FilePath).Name;
            }
            return fsr;

        }
    }
}
